package com.android.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.klm.ApkNameDao;
import com.android.klmgreendao.KlmApplication;
import com.android.R;
import com.android.klmgreendao.entity.ApkName;

import java.util.List;

/**
 * Created by klm_android on 2017/7/3.
 */

public class MainActivity extends Activity implements View.OnClickListener {
    private Button mAdd,mDelete,mUpdate,mFind;
    private TextView mContext;
    private ApkName mApkName;
    private ApkNameDao mApkNameDao;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initEvent();
        mApkNameDao = KlmApplication.getInstances().getDaoSession().getApkNameDao();
    }

    private void initEvent() {
        mAdd.setOnClickListener(this);
        mDelete.setOnClickListener(this);
        mUpdate.setOnClickListener(this);
        mFind.setOnClickListener(this);
    }

    private void initView() {
        mContext = (TextView) findViewById(R.id.textView);
        mAdd = (Button) findViewById(R.id.button);
        mDelete = (Button) findViewById(R.id.button2);
        mUpdate = (Button) findViewById(R.id.button3);
        mFind = (Button) findViewById(R.id.button4);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button:
                addDate();
                break;
            case R.id.button2:
                deleteDate();
                break;
            case R.id.button3:
                updateDate();
                break;
            case R.id.button4:
                findDate();
                break;
        }
    }

    /**
     * 增加数据
     */
    private void addDate() {
        long l = 0;
        if (mApkName != null && mApkName.getId() != null) {
            l = mApkName.getId();
        }
        mApkName = new ApkName(l+1,"name", "age");
        mApkNameDao.insert(mApkName);//添加一个
        mContext.setText(mApkName.getAppName());
    }

    /**
     * 删除数据
     */
    private void deleteDate() {
        deleteUserById(2);
    }

    /**
     * 根据主键删除User
     *
     * @param id User的主键Id
     */
    public void deleteUserById(long id) {
        mApkNameDao.deleteByKey(id);
    }

    /**
     * 更改数据
     */
    private void updateDate() {
        long l = mApkName.getId();
        mApkName = new ApkName(l,"name6", "age6");
        mApkNameDao.update(mApkName);
    }

    /**
     * 查找数据
     */
    private void findDate() {
        List<ApkName> apkNames = mApkNameDao.loadAll();
        String appName = "";
        for (int i = 0; i < apkNames.size(); i++) {
            appName += apkNames.get(i).getAppName()+",";
        }
        mContext.setText("查询全部数据==>"+appName);
    }
}
